package com.softer.chengxin.listener;

import com.softer.chengxin.common.domin.Common;
import com.softer.chengxin.login.dao.LoginDao;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author Gong Zhiyang
 * @date 2018/12/25
 */
@WebListener
public class MyHttpSessionListener implements HttpSessionListener, ServletRequestListener {
    @Autowired
    private LoginDao dao;
    /**
     * 在线人数
     */
    public static int online = 0;

    /**
     * 创建session
     *
     * @param se
     */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
    }

    /**
     * 销毁session
     *
     * @param se
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        //登陆类型
        String loginType = (String) session.getAttribute("loginType");
        if (Common.ONE.equals(loginType)) {
            String loginName = (String) session.getAttribute("loginName");
            //修改企业在线状态:不在线
            dao.updateCompanyOnline(loginName, Common.ZERO);
        }
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {

    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {

        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/api/UserInfo/Login")) {
            String loginType = request.getParameter("LoginType");
            if (Common.ONE.equals(loginType)) {
                online++;
            }
        }
    }
}
